//
//  SearchHistory.swift
//  TRHouse
//
//  Created by zhu xietong on 2018/5/11.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import Foundation

extension String{
    public static func any(_ any:Any?)->String{
        if let str = any as? String{
            return str
        }
        if let obj  = any{
            return "\(obj)"
        }
        return ""
    }
}



//
//class HouseSearchHistory: SearchHistory {
//    static var __shared:SearchHistory?
//    static var shared:SearchHistory{
//        get{
//            if let obj = SearchHistory.__shared{
//                return obj
//            }
//            let newObj = SearchHistory()
//            SearchHistory.__shared = newObj
//            return newObj
//        }
//    }
//}

extension SearchHistory{
    public enum Notice:String,NotifyType {
        case updateHistory = "updateHistory"
        case updateHot = "updateHot"
        
        public var name: Notification.Name{
            
            return "SearchHistory.\(Notice.self)\(self.rawValue)".notice_name
        }
    }
}



open class SearchHistory: NSObject {
    
    let p1 = "content"
    let p2 = "time"
    let p3 = "type"
    
    public static var db:DB.sqlite? = DB.sqlite(db_name: "user.db",bundle:Bundle(for: JoUser.self))
    
    public static var __shared:SearchHistory?
    public static var __shared1:SearchHistory?
    public static var __shared2:SearchHistory?
    public static var __shared3:SearchHistory?
    public static var __shared4:SearchHistory?
    public static var __shared5:SearchHistory?
    public static var __shared6:SearchHistory?
    public static var __shared7:SearchHistory?
    
    public static var shared:SearchHistory{
        get{
            if let obj = SearchHistory.__shared{
                return obj
            }
            let newObj = SearchHistory()
            SearchHistory.__shared = newObj
            return newObj
        }
    }
    
    public var historyType:String = "default"//该字段支持项目里多个类型的搜索记录
    
    public required override init() {
        super.init()
    }
    
    public func all(limit:Int? = nil) ->[[String:String]]
    {
        
        var list = [[String:String]]()
        
        if let db = SearchHistory.db
        {
            let create_tb = "create table if not exists search(sid integer primary key,\(p1) varchar(20),\(p2) varchar(20),\(p3) varchar(20))"
            db.exec(sql: create_tb)
            var sql = "select * from search where \(p3)='\(historyType)' order by time desc"
            if let num = limit{
                sql = "select * from search where \(p3)='\(historyType)' order by time desc limit \(num)"
            }
            let data = db.query(sql: sql)
            
            if data.count > 0 {
                
                for item in data
                {
                    
                    
                    var info = [String:String]()
                    info[p1] = String.any(item[p1])
                    info[p2] = String.any(item[p2])
                    info[p3] = String.any(item[p3])
                    
                    let sid = "sid"
                    info[sid] = String.any(item[sid])
                    
                    list.append(info)
                }
            }
        }
        return list
        
    }
    
    public func add(history:String)
    {
        if history.escapeHeadTailSpace().len < 1{
            return
        }
        let time = Date().time_stamp
        SearchHistory.db?.exec(sql: "create table if not exists search(sid integer primary key,\(p1) varchar(20),\(p2) varchar(20) \(p3) varchar(20))")
        
        let content = history
        if let item = self.findItem(content)
        {
            self.remove(item)
        }
        let sql = "insert into search(\(p1),\(p2),\(p3)) values('\(content)','\(time)','\(historyType)')"
        
        SearchHistory.db?.exec(sql: sql)
        __post(notify: Notice.updateHistory, object: nil, userInfo: ["history_type":historyType])
    }
    
    
    public func insert(_ item:[String:String])
    {
        let time = Date().time_stamp
        SearchHistory.db?.exec(sql: "create table if not exists search(sid integer primary key,\(p1) varchar(20),\(p2) varchar(20) \(p3) varchar(20))")
        
        if let content = item[p1]
        {
            if let item = self.findItem(content)
            {
                self.remove(item)
            }
            let sql = "insert into search(\(p1),\(p2),\(p3)) values('\(content)','\(time)','\(historyType)')"
            SearchHistory.db?.exec(sql: sql)
            __post(notify: Notice.updateHistory, object: nil, userInfo: ["history_type":historyType])
        }
        
    }
    
    public func clearAll()
    {
        //        let sql = "drop table search"
        let sql = "delete from search where \(p3)='\(historyType)'"
        
        SearchHistory.db?.exec(sql: sql)
        __post(notify: Notice.updateHistory, object: nil, userInfo: ["history_type":historyType])
        
    }
    
    static func clear()
    {
        let sql = "drop table search"
        SearchHistory.db?.exec(sql: sql)
        __post(notify: Notice.updateHistory, object: nil, userInfo: ["history_type":"all"])
    }
    
    
    public func findItem(_ content:String) ->[String:String]?
    {
        let sql = "select * from search where \(p1)='\(content)' and \(p3)='\(historyType)'"
        if let db = SearchHistory.db
        {
            let data = db.query(sql: sql)
            if data.count > 0 {
                
                for item in data
                {
                    var info = [String:String]()
                    info[p1] = String.any(item[p1])
                    info[p2] = String.any(item[p2])
                    info[p3] = String.any(item[p3])
                    
                    let sid = "sid"
                    info[sid] = String.any(item[sid])
                    return info
                }
            }
        }
        return nil
    }
    
    public func delete(_ history:String)
    {
        let content = history
        
        let sql = "delete from search where \(p1)='\(content)' and \(p3)='\(historyType)'"
        SearchHistory.db?.exec(sql: sql)
        __post(notify: Notice.updateHistory, object: nil, userInfo: ["history_type":historyType])
        
    }
    
    public func remove(_ item:[String:String])
    {
        if let content = item["content"]
        {
            let sql = "delete from search where content='\(content)' and \(p3)='\(historyType)'"
            SearchHistory.db?.exec(sql: sql)
            __post(notify: Notice.updateHistory, object: nil, userInfo: ["history_type":historyType])
        }
    }
}




